package cn.jxau.fukin.controller;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import cn.jxau.fukin.model.Card;
import cn.jxau.fukin.model.Rate;
import cn.jxau.fukin.model.Trade;
import cn.jxau.fukin.model.User;
import cn.jxau.fukin.service.IRateService;
import cn.jxau.fukin.service.IUserService;

/**
 * Description:转账功能
 * Title:TransferController
 * @author ChunFu-Lee
 * @date 2017-9-12 上午11:04:28
 */
@Controller
public class TransferController {

	@Autowired
	IUserService userService;
	@Autowired
	IRateService rateService;

	/**
	 * 转账页面
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/showTransferPage.do")
	public String showTransferPage(HttpServletRequest request) {
		String flag = (String) request.getSession().getAttribute("flag");
		if (flag != null) {

			return "forward:/WEB-INF/jsp/transfer.jsp";
		} else {
			return "forward:/user/showLoginPage.do";

		}
	}

	/**
	 * 转账业务
	 * @param mv
	 * @param trade
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/transfer.do")
	public ModelAndView transfer(ModelAndView mv, User user, Trade trade, HttpServletRequest request) {
		String password = request.getParameter("cPassword");
		String otheruName = request.getParameter("uName01");
		String otheruCId = request.getParameter("uCId01");
		User user01 = new User();
		user01.setuName(otheruName);
		user01.setuCId(otheruCId);

		String checkingUserMsg = userService.checkingUser(user);
		String checkingUser01Msg = userService.checkingUser(user01);
		if (!("true".equals(checkingUserMsg))) {
			request.getSession().setAttribute("msg", checkingUserMsg);
			mv.setViewName("redirect:/showTransferPage.do");
			return mv;
		}
		if (!("true".equals(checkingUser01Msg))) {
			request.getSession().setAttribute("msg", checkingUser01Msg);
			mv.setViewName("redirect:/showTransferPage.do");
			return mv;
		}
		User myUser = userService.queryUserInfo(user).get(0);
		User otherUser = userService.queryUserInfo(user01).get(0);

		// 我的卡
		Card myCard = new Card();
		myCard.setUser(myUser);
		myCard.setcId(user.getuCId());
		myCard.setcPassword(password);
		// 他的卡
		Card otherCard = new Card();
		otherCard.setUser(otherUser);
		otherCard.setcId(otheruCId);
		// 存款类型
		Rate rate = new Rate();
		rate.setDepositType(trade.getTradeType());

		String transfer = rateService.transfer(myCard, otherCard,
				trade.getTradeAmount().toString(), rate, null);
		System.out.println(transfer);
		request.getSession().setAttribute("successmsg", "转账成功");
		mv.setViewName("redirect:/showTransferPage.do");
		return mv;
	}
}
